#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QRegularExpression>
#include <QDateTime>
#include <QMessageBox>
#include <QJsonDocument>
#include <QJsonObject>
#include <QValueAxis>
#include <csignal>  // 添加这个头文件
#include <QNetworkInterface>  // 网络接口相关
#include <QHostAddress>       // IP地址处理
#include <QDebug>
#include <iostream>

double MainWindow::getCurrentValue(const QString& sensorName) const
{
    double value = 0.0;
    // 根据传感器名称返回对应的当前值
    if (sensorName == "CCD1") {
        value =  hwStatus.tempData.ccd1;
    } else if (sensorName == "CCD2") {
        value = hwStatus.tempData.ccd2;
    } else if (sensorName == "CCD3") {
        value = hwStatus.tempData.ccd3;
    } else if (sensorName == "CCD4") {
        value = hwStatus.tempData.ccd4;
    } else if (sensorName == "Base1") {
        value = hwStatus.tempData.base1;
    } else if (sensorName == "Base2") {
        value = hwStatus.tempData.base2;
    } else if (sensorName == "AbsorbCold") {
        value = hwStatus.tempData.absorbCold;
    } else if (sensorName == "Circuit") {
        value = hwStatus.tempData.circuit;
    }else if (sensorName == "Dewar") {
        value = hwStatus.tempData.dewar;
    } else if (sensorName == "Backup1") {
        value = hwStatus.tempData.backup1;
    } else if (sensorName == "Backup2") {
        value = hwStatus.tempData.backup2;
    } else if (sensorName == "Output") {
        value = hwStatus.tempData.outputPower;
    }else if (sensorName == "Vacuum") {
        value = hwStatus.currentVacuum;
    }
    //else if (sensorName == "Current") {
        //return hwStatus.currentCurrent; // 假设您有一个currentCurrent成员变量
    //}
    //LOG_TEMP_VAC(QString("VALUE = %1").arg(value));
    qWarning() << "Unknown sensor name:" << sensorName;
    return value;
}


void MainWindow::updateTempChartTimeRange(int hours)
{
    auto axisX = qobject_cast<QDateTimeAxis*>(hwStatus.multiTempChart->axes(Qt::Horizontal)[0]);
    if (axisX) {
        QDateTime now = QDateTime::currentDateTime();
        axisX->setRange(now.addSecs(-hours * 300), now);

        updateTemperatureCurves();
    }
}

void MainWindow::updateVacuumChartTimeRange(int hours)
{
    auto axisX = qobject_cast<QDateTimeAxis*>(vacuumChart->axes(Qt::Horizontal)[0]);
    if (axisX) {
        QDateTime now = QDateTime::currentDateTime();
        axisX->setRange(now.addSecs(-hours * 300), now);

        // 可选：自动调整Y轴范围
        auto axisY = qobject_cast<QLogValueAxis*>(vacuumChart->axes(Qt::Vertical)[0]);
        if (axisY) {
            double minY = 1e-4;
            double maxY = qMax(hwStatus.currentVacuum * 1.1, 1e-2);
            axisY->setRange(minY, maxY);
        }
    }
}

void MainWindow::initializeCharts()
{
    // 在创建新系列前清理旧系列
    qDeleteAll(hwStatus.tempSeriesMap);
    hwStatus.tempSeriesMap.clear();

    vacuumChart = new QChart();
    vacuumChart->setTitle("Vacuum Chart");
    vacuumSeries = new QLineSeries();
    vacuumChart->addSeries(vacuumSeries);


    QDateTimeAxis *vacuumAxisX = new QDateTimeAxis();
    vacuumAxisX->setTitleText("Time");
    vacuumAxisX->setFormat("MM-dd hh:mm");
    vacuumAxisX->setRange(QDateTime::currentDateTime().addSecs(-300), QDateTime::currentDateTime());
    vacuumChart->addAxis(vacuumAxisX, Qt::AlignBottom);

    //新的对数坐标
    QLogValueAxis *logAxisY = new QLogValueAxis();
    logAxisY->setRange(1e-5, 1e-2);
    logAxisY->setTitleText("Pressure (Pa)");
    logAxisY->setLabelFormat("%.1e");
    vacuumChart->addAxis(logAxisY, Qt::AlignLeft);
    vacuumSeries->attachAxis(logAxisY);

    //vacuumChart->addAxis(vacuumAxisY, Qt::AlignLeft);
    vacuumSeries->attachAxis(vacuumAxisX);
    //vacuumSeries->attachAxis(vacuumAxisY);
    /*vacuumSeries->append(0, 2e-5);
    vacuumSeries->append(1, 1e-3);
    vacuumSeries->append(2, 0.8e-2);*/
    ui->vacuumChartView_2->setChart(vacuumChart);
    ui->vacuumChartView_2->setRenderHint(QPainter::Antialiasing);

    // 多温度曲线图表
    hwStatus.multiTempChart = new QChart();
    //hwStatus.multiTempChart->setTitle("Multi Temp Chart");

    // 创建复选框容器
    tempCheckBoxGroup = new QGroupBox("Show", this);
    QVBoxLayout *checkBoxLayout = new QVBoxLayout(tempCheckBoxGroup);

    // 为每个测温点创建曲线系列和复选框
    QStringList tempPoints = {
        "CCD1", "CCD2", "CCD3", "CCD4",
         "Base", "AbsorbCold",
        "Circuit", "Dewar","Output","Temp_set"
    };

    QList<QColor> colors = {
        Qt::darkYellow, Qt::green, Qt::blue, Qt::cyan,
        Qt::magenta, Qt::darkRed,
        Qt::darkGreen, Qt::darkBlue,
        Qt::darkCyan, Qt::darkMagenta
    };

    for (int i = 0; i < tempPoints.size(); ++i) {
        // 创建曲线系列
        QtCharts::QLineSeries *series = new QtCharts::QLineSeries();
        series->setName(tempPoints[i]);
        series->setColor(colors[i]);
        hwStatus.tempSeriesMap[tempPoints[i]] = series;
        hwStatus.multiTempChart->addSeries(series);

        // 创建对应的复选框
        QCheckBox *checkBox = new QCheckBox(tempPoints[i], tempCheckBoxGroup);
        checkBox->setChecked(true); // 默认选中
        checkBox->setStyleSheet(QString("color: %1").arg(colors[i].name()));
        tempCheckBoxes[tempPoints[i]] = checkBox;
        checkBoxLayout->addWidget(checkBox);

        // 连接信号槽
        connect(checkBox, &QCheckBox::stateChanged, this, &MainWindow::updateTemperatureCurves);
    }

    // 将复选框容器添加到UI
    ui->verticalLayout->insertWidget(0, tempCheckBoxGroup); // 根据实际布局调整

    // 设置坐标轴
    //QValueAxis *axisX = new QValueAxis();
    //axisX->setTitleText("Time (Min)");
    //axisX->setRange(0, 60);
    //axisX->setLabelFormat("%.1f");
    //hwStatus.multiTempChart->addAxis(axisX, Qt::AlignBottom);
    // 使用日期时间轴
    QDateTimeAxis *axisX = new QDateTimeAxis();
    //axisX->setTitleText("Time");
    axisX->setFormat("MM-dd hh:mm");
    axisX->setRange(QDateTime::currentDateTime().addSecs(-300), QDateTime::currentDateTime());
    hwStatus.multiTempChart->addAxis(axisX, Qt::AlignBottom);


    QValueAxis *axisY = new QValueAxis();
    //axisY->setTitleText("Temp (°C)");
    axisY->setRange(-120, 100);
    hwStatus.multiTempChart->addAxis(axisY, Qt::AlignLeft);

    // 将系列附加到坐标轴
    for (auto series : hwStatus.tempSeriesMap) {
        series->attachAxis(axisX);
        series->attachAxis(axisY);
    }

    // 将图表添加到UI
    ui->multiTempChartView->setChart(hwStatus.multiTempChart);
    ui->multiTempChartView->setRenderHint(QPainter::Antialiasing);
}

void MainWindow::onbtnReadTemp() {
    /*if (!hwStatus.isConnected) {
        QMessageBox::warning(this, "警告", "未连接到设备！");
        return;
    }*/

    sendActionCommandToMCU("temp_read");
}

void MainWindow::checkMCUConnectionStatus() {
    QDateTime now = QDateTime::currentDateTime();

    // 温度连接状态
    bool tempConnected = hwStatus.lastTempResponseTime.isValid() &&
                         hwStatus.lastTempResponseTime.msecsTo(now) < 15000;

    // 真空度连接状态
    bool vacuumConnected = hwStatus.lastVacuumResponseTime.isValid() &&
                           hwStatus.lastVacuumResponseTime.msecsTo(now) < 15000;

    bool isValid = hwStatus.lastVacuumResponseTime.isValid();
    double time = hwStatus.lastVacuumResponseTime.msecsTo(now);
    QString clientKey = QString("%1:%2").arg(hwStatus.lastVacuumResponseTime.toString("yyyyMMddhhmmss")).arg(isValid);

    // 更新状态
    hwStatus.tempConnected = tempConnected;
    hwStatus.vacuumConnected = vacuumConnected;
    updateConnectionUI();
}


void MainWindow::updateConnectionUI() {
    // 温度连接状态
    if (hwStatus.tempConnected) {
        //ui->labelTempStatus->setText("已连接");
        ui->lblCurrentTemp_2->setStyleSheet("color: green;");
    } else {
        ui->lblCurrentTemp_2->setText("Not connected");
        ui->lblCurrentTemp_2->setStyleSheet("color: red;");
    }

    // 真空度连接状态
    if (hwStatus.vacuumConnected) {
        //ui->labelVacuumStatus->setText("已连接");
        ui->lblStatus_3->setStyleSheet("color: green;");
    } else {
        ui->lblStatus_3->setText("Not connected");
        ui->lblStatus_3->setStyleSheet("color: red;");
    }
}
void MainWindow::processTempHeartData() {
    QElapsedTimer timer;
    timer.start();

    //qint64 elapsedSec = m_startTime.secsTo(QDateTime::currentDateTime());
    while (TempHeartSocket->hasPendingDatagrams()) {
        QByteArray datagram;
        datagram.resize(TempHeartSocket->pendingDatagramSize());
        QHostAddress sender;
        quint16 senderPort;

        // 读取UDP数据报
        qint64 bytesRead = TempHeartSocket->readDatagram(
            datagram.data(),
            datagram.size(),
            &sender,
            &senderPort
            );

        if (bytesRead == -1) {
            writeAutoUpdateLog("读取MCU数据失败: " + TempHeartSocket->errorString());
            continue;
        }

        QString data = QString(datagram).trimmed();
        LOG_TEMP_VAC("Received MCU response: " + data);
        if (data.startsWith("CCD_3:")) {
            if (!m_isRegistered) {
                m_isRegistered = true;
                LOG_GENERAL("MCU heartbeat received, registration successful");
            }
            hwStatus.lastTempResponseTime = QDateTime::currentDateTime();
            // 分割数据为键值对（示例数据格式：CCD_1:55.35&&CCD_2:55.48...）
            QStringList tempPairs = data.split("&&");

            double ccdSum = 0.0;
            int ccdCount = 0;

            // 解析每个温度点
            for (const QString &pair : tempPairs) {
                QStringList keyValue = pair.split(':');
                if (keyValue.size() != 2) {
                    writeAutoUpdateLog("无效的温度数据格式: " + pair);
                    continue;
                }

                QString key = keyValue[0].trimmed();
                QString valueStr = keyValue[1].trimmed();
                bool ok;
                double value = valueStr.toDouble(&ok);

                if (!ok) {
                    writeAutoUpdateLog("无效的温度数值: " + valueStr);
                    continue;
                }

                // 更新温度数据到结构体
                if (key == "CCD_1") {
                    hwStatus.tempData.ccd1 = value;
                    ccdSum += value;
                    ccdCount++;
                    //LOG_GENERAL(QString("ccdSum Current: %1 ccdCount: %2").arg(ccdSum).arg(ccdCount));
                } else if (key == "CCD_2") {
                    hwStatus.tempData.ccd2 = value;
                    ccdSum += value;
                    ccdCount++;
                    //LOG_GENERAL(QString("ccdSum Current: %1 ccdCount: %2").arg(ccdSum).arg(ccdCount));
                } else if (key == "CCD_3") {
                    hwStatus.tempData.ccd3 = value;
                    ccdSum += value;
                    ccdCount++;
                    //LOG_GENERAL(QString("ccdSum Current: %1 ccdCount: %2").arg(ccdSum).arg(ccdCount));
                } else if (key == "CCD_4") {
                    hwStatus.tempData.ccd4 = value;
                    ccdSum += value;
                    ccdCount++;
                    //LOG_GENERAL(QString("ccdSum Current: %1 ccdCount: %2").arg(ccdSum).arg(ccdCount));
                } else if (key == "Base_1") {
                    hwStatus.tempData.base1 = value;
                } else if (key == "Base_2") {
                    hwStatus.tempData.base2 = value;
                } else if (key == "Absorbent_cold") {
                    hwStatus.tempData.absorbCold = value;
                } else if (key == "Drive_circuit") {
                    hwStatus.tempData.circuit = value;
                } else if (key == "Dewar") {
                    hwStatus.tempData.dewar = value;
                } else if (key == "Backup1") {
                    hwStatus.tempData.backup1 = value;
                } else if (key == "Backup2") {
                    hwStatus.tempData.backup2 = value;
                } else if (key == "output") {
                    hwStatus.tempData.outputPower = value;
                } else if (key == "temp_set") {
                    hwStatus.tempData.targetTemp = value;
                } else {
                    writeAutoUpdateLog("未知的温度点: " + key);
                }
            }

            // 计算CCD1-CCD4的平均温度
            if (ccdCount > 0) {
                hwStatus.currentTemp = ccdSum / ccdCount;
                //LOG_GENERAL(QString("ccdSum Current: %1 ccdCount: %2").arg(ccdSum).arg(ccdCount));

                double tempDiff = qAbs(hwStatus.currentTemp - hwStatus.tempData.targetTemp);
                hwStatus.tempStabilized = (tempDiff <= 1.0); // 温差不超过1℃视为稳定
                QString style;
                if (hwStatus.tempStabilized) {
                    style = "color: green; font-weight: bold;"; // 稳定时蓝色
                } else {
                    style = "color: red; font-weight: bold;"; // 不稳定时黄色
                }
                LOG_TEMP_VAC(QString("hwStatus.currentTemp: %1 ").arg(hwStatus.currentTemp));
                ui->lblCurrentTemp_2->setStyleSheet(style);
                ui->lblCurrentTemp_3->setStyleSheet(style);
                ui->lblCurrentTemp_2->setText(QString::number(hwStatus.currentTemp, 'f', 2) + " °C");
                ui->lblCurrentTemp_3->setText(QString::number(hwStatus.currentTemp, 'f', 2) + " °C");
            }

            // 触发UI更新
            QMetaObject::invokeMethod(this, &MainWindow::updateTemperatureCurves);
            QMetaObject::invokeMethod(this, &MainWindow::updateTemperatureDisplay);
            QMetaObject::invokeMethod(this, &MainWindow::updateHeartbeatStatus);
        }
    }
}
void MainWindow::processVacuumHeartData() {
    QElapsedTimer timer;
    timer.start();

    //qint64 elapsedSec = m_startTime.secsTo(QDateTime::currentDateTime());
    while (VacuumHeartSocket->hasPendingDatagrams()) {
        QByteArray datagram;
        datagram.resize(VacuumHeartSocket->pendingDatagramSize());
        QHostAddress sender;
        quint16 senderPort;

        // 读取UDP数据报
        qint64 bytesRead = VacuumHeartSocket->readDatagram(
            datagram.data(),
            datagram.size(),
            &sender,
            &senderPort
            );

        if (bytesRead == -1) {
            writeAutoUpdateLog("读取MCU数据失败: " + VacuumHeartSocket->errorString());
            continue;
        }

        QString data = QString(datagram).trimmed();
        LOG_TEMP_VAC("Received MCU response: " + data);
        if (data.startsWith("vaccu_read:")) {  // 协议前缀是"vaccu_read:"

            QString payload = data.mid(11).trimmed();  // 去掉前缀
            if (payload.length() >= 15) {  // 确保数据长度足够
                hwStatus.lastVacuumResponseTime = QDateTime::currentDateTime();
                bool ok = true;
                // 提取有效部分（11-16位）
                QString valuePart = payload.mid(10, 6);  // 从0开始计数，11-16位是索引10-15
                if (valuePart.length() == 6) {
                    // 解析有效数字（前4位）
                    double mantissa = valuePart.left(4).toDouble(&ok);
                    ok = true;
                    if (ok) {
                        // 解析指数（后2位减去21）
                        int exponent = valuePart.mid(4, 2).toInt(&ok) - 21;
                        //QString debuginfo= QString("有效部分%1 有效数字%2 指数%3").arg(valuePart).arg(mantissa).arg(exponent);
                        //writeAutoUpdateLog("真空度debuginfo" + debuginfo);
                        if (ok) {
                            // 计算最终真空度值
                            double vacuum = mantissa * qPow(10, exponent);
                            hwStatus.currentVacuum = vacuum;
                            hwStatus.vacuumHistory.append(vacuum);
                            LOG_TEMP_VAC(QString("hwStatus.currentVacuum: %1 ").arg(hwStatus.currentVacuum));

                            // 限制历史数据长度（如保留最近1小时数据，每秒1个点）
                            if (hwStatus.vacuumHistory.size() > 300) {
                                hwStatus.vacuumHistory.removeFirst();
                            }
                            //updateVacuumData();
                        }
                    }

                }
            }
            // 触发UI更新
            QMetaObject::invokeMethod(this, &MainWindow::updateVacuumData);
        }
    }
}

void MainWindow::processMCUActionData() {
    while (McuActionSocket->hasPendingDatagrams()) {
        QByteArray datagram;
        datagram.resize(McuActionSocket->pendingDatagramSize());
        McuActionSocket->readDatagram(datagram.data(), datagram.size());

        QString response = QString::fromUtf8(datagram).trimmed();

        if (response == "cooler_set=ok") {
            ui->statusbar->showMessage("设置成功!", 2000);
            //m_powerOnBtn->setEnabled(false);
            //m_powerOffBtn->setEnabled(true);
            //QTimer::singleShot(2000, [this](){
                //m_powerOnBtn->setEnabled(true);
                //m_powerOffBtn->setEnabled(true);
            //});
        }
        else if (response.startsWith("cooler_set=error")) {
            ui->statusbar->showMessage("设置失败: " + response.mid(16), 3000);
        }
        else if (response.startsWith("temp_set=:")){
            LOG_GENERAL("温度set to:" + response);
        }
    }
}

void MainWindow::processIOHeartData() {
    while (IOHeartSocket->hasPendingDatagrams()) {
        QByteArray datagram;
        datagram.resize(IOHeartSocket->pendingDatagramSize());
        QHostAddress sender;
        quint16 senderPort;

        qint64 bytesRead = IOHeartSocket->readDatagram(
            datagram.data(), datagram.size(), &sender, &senderPort);

        if (bytesRead == -1) {
            writeAutoUpdateLog("读取MCU数据失败: " + IOHeartSocket->errorString());
            continue;
        }

        QString data = QString(datagram).trimmed();
        LOG_TEMP_VAC("Received MCU response: " + data);

        if (data.startsWith("io_status_read:")) {
            IOStatus status = parseIOStatus(data);

            // 更新UI按钮状态（线程安全）
            QMetaObject::invokeMethod(this, [this, status]() {
                updatePowerButtonStates(btnCameraPowerOn, btnCameraPowerOff, status.cameraPower);
                updatePowerButtonStates(btnHeatPowerOn, btnHeatPowerOff, status.heatingPower);
                updatePowerButtonStates(btnVaccuPowerOn, btnVaccuPowerOff, status.vacuumPower);
            });
            m_currentIOStatus = status;
        }
    }
}

/*void MainWindow::processMCUData() {

    QElapsedTimer timer;
    timer.start();

    //qint64 elapsedSec = m_startTime.secsTo(QDateTime::currentDateTime());
    while (mcuSocket->hasPendingDatagrams()) {
        QByteArray datagram;
        datagram.resize(mcuSocket->pendingDatagramSize());
        QHostAddress sender;
        quint16 senderPort;

        // 读取UDP数据报
        qint64 bytesRead = mcuSocket->readDatagram(
            datagram.data(),
            datagram.size(),
            &sender,
            &senderPort
            );

        if (bytesRead == -1) {
            writeAutoUpdateLog("读取MCU数据失败: " + mcuSocket->errorString());
            continue;
        }

        QString data = QString(datagram).trimmed();
        LOG_TEMP_VAC("Received MCU response: " + data);

        // 只处理温度查询响应
        if (data.startsWith("CCD_3:")) {
            if (!m_isRegistered) {
                m_isRegistered = true;
                LOG_GENERAL("MCU heartbeat received, registration successful");
            }
            hwStatus.lastTempResponseTime = QDateTime::currentDateTime();
            // 分割数据为键值对（示例数据格式：CCD_1:55.35&&CCD_2:55.48...）
            QStringList tempPairs = data.split("&&");

            double ccdSum = 0.0;
            int ccdCount = 0;

            // 解析每个温度点
            for (const QString &pair : tempPairs) {
                QStringList keyValue = pair.split(':');
                if (keyValue.size() != 2) {
                    writeAutoUpdateLog("无效的温度数据格式: " + pair);
                    continue;
                }

                QString key = keyValue[0].trimmed();
                QString valueStr = keyValue[1].trimmed();
                bool ok;
                double value = valueStr.toDouble(&ok);

                if (!ok) {
                    writeAutoUpdateLog("无效的温度数值: " + valueStr);
                    continue;
                }

                // 更新温度数据到结构体
                if (key == "CCD_1") {
                    hwStatus.tempData.ccd1 = value;
                    ccdSum += value;
                    ccdCount++;
                    //LOG_GENERAL(QString("ccdSum Current: %1 ccdCount: %2").arg(ccdSum).arg(ccdCount));
                } else if (key == "CCD_2") {
                    hwStatus.tempData.ccd2 = value;
                    ccdSum += value;
                    ccdCount++;
                    //LOG_GENERAL(QString("ccdSum Current: %1 ccdCount: %2").arg(ccdSum).arg(ccdCount));
                } else if (key == "CCD_3") {
                    hwStatus.tempData.ccd3 = value;
                    ccdSum += value;
                    ccdCount++;
                    //LOG_GENERAL(QString("ccdSum Current: %1 ccdCount: %2").arg(ccdSum).arg(ccdCount));
                } else if (key == "CCD_4") {
                    hwStatus.tempData.ccd4 = value;
                    ccdSum += value;
                    ccdCount++;
                    //LOG_GENERAL(QString("ccdSum Current: %1 ccdCount: %2").arg(ccdSum).arg(ccdCount));
                } else if (key == "Base_1") {
                    hwStatus.tempData.base1 = value;
                } else if (key == "Base_2") {
                    hwStatus.tempData.base2 = value;
                } else if (key == "Absorbent_cold") {
                    hwStatus.tempData.absorbCold = value;
                } else if (key == "Drive_circuit") {
                    hwStatus.tempData.circuit = value;
                } else if (key == "Dewar") {
                    hwStatus.tempData.dewar = value;
                } else if (key == "Backup1") {
                    hwStatus.tempData.backup1 = value;
                } else if (key == "Backup2") {
                    hwStatus.tempData.backup2 = value;
                } else if (key == "output") {
                    hwStatus.tempData.outputPower = value;
                } else if (key == "temp_set") {
                    hwStatus.tempData.targetTemp = value;
                } else {
                    writeAutoUpdateLog("未知的温度点: " + key);
                }
            }

            // 计算CCD1-CCD4的平均温度
            if (ccdCount > 0) {
                hwStatus.currentTemp = ccdSum / ccdCount;
                //LOG_GENERAL(QString("ccdSum Current: %1 ccdCount: %2").arg(ccdSum).arg(ccdCount));

                double tempDiff = qAbs(hwStatus.currentTemp - hwStatus.tempData.targetTemp);
                hwStatus.tempStabilized = (tempDiff <= 1.0); // 温差不超过1℃视为稳定
                QString style;
                if (hwStatus.tempStabilized) {
                    style = "color: green; font-weight: bold;"; // 稳定时蓝色
                } else {
                    style = "color: red; font-weight: bold;"; // 不稳定时黄色
                }
                LOG_TEMP_VAC(QString("hwStatus.currentTemp: %1 ").arg(hwStatus.currentTemp));
                ui->lblCurrentTemp_2->setStyleSheet(style);
                ui->lblCurrentTemp_3->setStyleSheet(style);
                ui->lblCurrentTemp_2->setText(QString::number(hwStatus.currentTemp, 'f', 2) + " °C");
                ui->lblCurrentTemp_3->setText(QString::number(hwStatus.currentTemp, 'f', 2) + " °C");
            }

            // 触发UI更新
            QMetaObject::invokeMethod(this, &MainWindow::updateTemperatureCurves);
            QMetaObject::invokeMethod(this, &MainWindow::updateTemperatureDisplay);
            QMetaObject::invokeMethod(this, &MainWindow::updateHeartbeatStatus);
        }
        else if (data.startsWith("vaccu_read:")) {  // 协议前缀是"vaccu_read:"

            QString payload = data.mid(11).trimmed();  // 去掉前缀
            if (payload.length() >= 15) {  // 确保数据长度足够
                hwStatus.lastVacuumResponseTime = QDateTime::currentDateTime();
                bool ok = true;
                // 提取有效部分（11-16位）
                QString valuePart = payload.mid(10, 6);  // 从0开始计数，11-16位是索引10-15
                if (valuePart.length() == 6) {
                    // 解析有效数字（前4位）
                    double mantissa = valuePart.left(4).toDouble(&ok);
                    ok = true;
                    if (ok) {
                        // 解析指数（后2位减去21）
                        int exponent = valuePart.mid(4, 2).toInt(&ok) - 21;
                        //QString debuginfo= QString("有效部分%1 有效数字%2 指数%3").arg(valuePart).arg(mantissa).arg(exponent);
                        //writeAutoUpdateLog("真空度debuginfo" + debuginfo);
                        if (ok) {
                            // 计算最终真空度值
                            double vacuum = mantissa * qPow(10, exponent);
                            hwStatus.currentVacuum = vacuum;
                            hwStatus.vacuumHistory.append(vacuum);
                            LOG_TEMP_VAC(QString("hwStatus.currentVacuum: %1 ").arg(hwStatus.currentVacuum));

                            // 限制历史数据长度（如保留最近1小时数据，每秒1个点）
                            if (hwStatus.vacuumHistory.size() > 300) {
                                hwStatus.vacuumHistory.removeFirst();
                            }
                            //updateVacuumData();
                        }
                    }

                }
            }
            // 触发UI更新
            QMetaObject::invokeMethod(this, &MainWindow::updateVacuumData);
        }
        else if (data.startsWith("temp_set=:")){
            writeAutoUpdateLog("温度set to:" + data);
        }
    }

//    std::cout << QString("Function: %1 took: ").arg(__func__).toStdString() << timer.elapsed() << "milliseconds\n";
}*/

void MainWindow::updateVacuumData()
{
    QDateTime currentTime = QDateTime::currentDateTime();

    // 添加新数据点
    vacuumDataPoints.append(qMakePair(currentTime, hwStatus.currentVacuum));


    ui->lblStatus_3->setText(QString::number(hwStatus.currentVacuum, 'e', 3));

    vacuumSeries->append(currentTime.toMSecsSinceEpoch(), hwStatus.currentVacuum);


    // 更新图表
    //vacuumSeries->clear();
    //for (const auto &point : vacuumDataPoints) {
    // vacuumSeries->append(point.first.toMSecsSinceEpoch(), point.second);
    //}

    // 调整X轴范围(显示最近1小时)
    auto axisX = qobject_cast<QDateTimeAxis*>(vacuumChart->axes(Qt::Horizontal)[0]);
    if (axisX) {
        axisX->setRange(currentTime.addSecs(-300), currentTime);
    }
    // 动态调整Y轴范围（对数坐标）
    auto axisY = qobject_cast<QLogValueAxis*>(vacuumChart->axes(Qt::Vertical)[0]);
    if (axisY) {
        // 自动计算Y轴范围（保留10%边距）
        double minY = 8e-4; // 最小固定为8e-4 Pa
        double maxY = qMax(hwStatus.currentVacuum * 1.1, 1e-2); // 当前值的110%或1e-2 Pa
        axisY->setRange(minY, maxY);
    }
}

void MainWindow::updateTemperatureData()
{
    // 获取当前时间
    QDateTime currentTime = QDateTime::currentDateTime();

    // 更新所有温度曲线的数据（使用时间戳作为X轴）
    hwStatus.tempSeriesMap["CCD1"]->append(currentTime.toMSecsSinceEpoch(), hwStatus.tempData.ccd1);
    hwStatus.tempSeriesMap["CCD2"]->append(currentTime.toMSecsSinceEpoch(), hwStatus.tempData.ccd2);
    hwStatus.tempSeriesMap["CCD3"]->append(currentTime.toMSecsSinceEpoch(), hwStatus.tempData.ccd3);
    hwStatus.tempSeriesMap["CCD4"]->append(currentTime.toMSecsSinceEpoch(), hwStatus.tempData.ccd4);
    hwStatus.tempSeriesMap["Base"]->append(currentTime.toMSecsSinceEpoch(), hwStatus.tempData.base1);
    hwStatus.tempSeriesMap["AbsorbCold"]->append(currentTime.toMSecsSinceEpoch(), hwStatus.tempData.absorbCold);
    hwStatus.tempSeriesMap["Circuit"]->append(currentTime.toMSecsSinceEpoch(), hwStatus.tempData.circuit);
    hwStatus.tempSeriesMap["Dewar"]->append(currentTime.toMSecsSinceEpoch(), hwStatus.tempData.dewar);
    hwStatus.tempSeriesMap["Output"]->append(currentTime.toMSecsSinceEpoch(), hwStatus.tempData.outputPower);
    hwStatus.tempSeriesMap["Temp_set"]->append(currentTime.toMSecsSinceEpoch(), hwStatus.tempData.targetTemp);

    // 动态调整X轴范围（显示最近60分钟的数据）
    auto axisX = qobject_cast<QDateTimeAxis*>(hwStatus.multiTempChart->axes(Qt::Horizontal)[0]);
    if (axisX) {
        QDateTime minTime = currentTime.addSecs(-60 * 5); // 60分钟前
        axisX->setRange(minTime, currentTime);
    }

    // 可选：限制数据点数量（如果性能有问题时启用）
    /*
    const int maxPoints = 3600; // 保留1小时数据（假设每秒1个点）
    for (auto &series : hwStatus.tempSeriesMap) {
        if (series->count() > maxPoints) {
            series->removePoints(0, series->count() - maxPoints);
        }
    }
    */
}

void MainWindow::clearOldData()
{
    const qint64 retentionPeriod = 1 * 3600 * 1000; // 保留4小时（毫秒）
    qint64 cutoff = QDateTime::currentMSecsSinceEpoch() - retentionPeriod;

    // 清理温度曲线
    for (auto &series : hwStatus.tempSeriesMap) {
        while (series->count() > 0 && series->at(0).x() < cutoff) {
            series->remove(0);
        }
    }

    // 清理真空度曲线（如果有需要）
    while (vacuumSeries->count() > 0 && vacuumSeries->at(0).x() < cutoff) {
        vacuumSeries->remove(0);
    }
}
/*
void MainWindow::updateVacuumData()
{
    //static int timeCounter = 0;
    double xValue = timeCounter / 60.0; // 转换为分钟

    // 添加新数据点
    vacuumSeries->append(xValue, hwStatus.currentVacuum);

    if (hwStatus.currentVacuum != 1000) {
        ui->lblStatus_3->setText(QString::number(hwStatus.currentVacuum, 'e', 3));
    }

    //ui->lblStatus_4->setText(QString::number(hwStatus.currentVacuum, 'e', 3));
    //ui->lblStatus_5->setText(QString::number(hwStatus.currentVacuum, 'e', 3));
    // 动态调整X轴范围，显示最近60分钟的数据
    auto axisX = qobject_cast<QValueAxis*>(vacuumChart->axes(Qt::Horizontal)[0]);
    if (axisX) {
        double minX = qMax(0.0, xValue - 60.0); // 显示最近60分钟
        double maxX = xValue;
        axisX->setRange(minX, maxX);
    }

    // 动态调整Y轴范围（对数坐标）
    auto axisY = qobject_cast<QLogValueAxis*>(vacuumChart->axes(Qt::Vertical)[0]);
    if (axisY) {
        // 自动计算Y轴范围（保留10%边距）
        double minY = 8e-4; // 最小固定为8e-4 Pa
        double maxY = qMax(hwStatus.currentVacuum * 1.1, 1e-2); // 当前值的110%或1e-2 Pa
        axisY->setRange(minY, maxY);
    }

    // 可选：限制数据点数量（如果性能有问题）

    if (timeCounter > 3600 * 2) { // 保留2小时数据
        vacuumSeries->removePoints(0, vacuumSeries->count() - 3600 * 2);
    }

    // 检查报警
    //checkAllAlarms();
}*/
/*
void MainWindow::updateTemperatureData()
{
    //static int timeCounter = 0;
    double xValue = timeCounter / 60.0; // 转换为分钟

    // 更新所有曲线的数据
    hwStatus.tempSeriesMap["CCD1"]->append(xValue, hwStatus.tempData.ccd1);
    hwStatus.tempSeriesMap["CCD2"]->append(xValue, hwStatus.tempData.ccd2);
    hwStatus.tempSeriesMap["CCD3"]->append(xValue, hwStatus.tempData.ccd3);
    hwStatus.tempSeriesMap["CCD4"]->append(xValue, hwStatus.tempData.ccd4);
    //hwStatus.tempSeriesMap["Base1"]->append(xValue, hwStatus.tempData.base1);
    hwStatus.tempSeriesMap["Base2"]->append(xValue, hwStatus.tempData.base2);
    hwStatus.tempSeriesMap["AbsorbCold"]->append(xValue, hwStatus.tempData.absorbCold);
    hwStatus.tempSeriesMap["Circuit"]->append(xValue, hwStatus.tempData.circuit);
    hwStatus.tempSeriesMap["Dewar"]->append(xValue, hwStatus.tempData.dewar);
    //hwStatus.tempSeriesMap["Backup1"]->append(xValue, hwStatus.tempData.backup1);
    //hwStatus.tempSeriesMap["Backup2"]->append(xValue, hwStatus.tempData.backup2);
    hwStatus.tempSeriesMap["Output"]->append(xValue, hwStatus.tempData.outputPower);
    hwStatus.tempSeriesMap["Temp_set"]->append(xValue, hwStatus.tempData.targetTemp);


    timeCounter++;

    // 动态调整X轴范围，显示最近60分钟的数据
    auto axisX = qobject_cast<QValueAxis*>(hwStatus.multiTempChart->axes(Qt::Horizontal)[0]);
    if (axisX) {
        double minX = qMax(0.0, xValue - 60.0); // 显示最近60分钟
        double maxX = xValue;
        axisX->setRange(minX, maxX);
    }

    // 限制数据点数量（可选，如果性能有问题时启用）

    if (timeCounter > 3600 * 2) { // 保留2小时数据
        for (auto &series : hwStatus.tempSeriesMap) {
            if (series->count() > 3600 * 2) {
                series->removePoints(0, series->count() - 3600 * 2);
            }
        }
    }

    // 检查报警
    //checkAllAlarms();
}*/

void MainWindow::updateTemperatureCurves()
{
    // 只控制曲线的可见性，不影响数据更新
    for (auto &series : hwStatus.tempSeriesMap) {
        bool visible = tempCheckBoxes[series->name()]->isChecked();
        series->setVisible(visible);
    }

    // 自动调整Y轴范围
    auto yAxis = qobject_cast<QValueAxis*>(hwStatus.multiTempChart->axes(Qt::Vertical)[0]);
    if (yAxis) {
        double min = std::numeric_limits<double>::max();
        double max = std::numeric_limits<double>::lowest();

        // 只考虑当前可见的曲线
        for (const auto &series : hwStatus.tempSeriesMap) {
            if (series->isVisible()) {
                auto points = series->pointsVector();
                for (const QPointF &point : points) {
                    if (!qIsNaN(point.y())) {
                        min = qMin(min, point.y());
                        max = qMax(max, point.y());
                    }
                }
            }
        }

        // 设置Y轴范围（保留10%边距）
        if (min < max) {
            double margin = (max - min) * 0.1;
            yAxis->setRange(min - margin, max + margin);
        }
    }
}

void MainWindow::updateTemperatureDisplay() {
    // CCD温度
    ui->labelCCD1->setText(formatTemperature(hwStatus.tempData.ccd1));
    ui->labelCCD2->setText(formatTemperature(hwStatus.tempData.ccd2));
    ui->labelCCD3->setText(formatTemperature(hwStatus.tempData.ccd3));
    ui->labelCCD4->setText(formatTemperature(hwStatus.tempData.ccd4));

    // 基板温度
    //ui->labelBase1->setText(formatTemperature(hwStatus.tempData.base1));
    ui->labelBase->setText(formatTemperature(hwStatus.tempData.base1));

    // 吸收体与电路
    ui->labelAbsorbCold->setText(formatTemperature(hwStatus.tempData.absorbCold));
    ui->labelCircuit->setText(formatTemperature(hwStatus.tempData.circuit));
    //ui->labelCircuit2->setText(formatTemperature(hwStatus.tempData.circuit2));

    // 其他设备
    ui->labelDewar->setText(formatTemperature(hwStatus.tempData.dewar));
    //ui->labelBackup1->setText(formatTemperature(hwStatus.tempData.backup1));
    //ui->labelBackup2->setText(formatTemperature(hwStatus.tempData.backup2));

    // 功率与目标温度
    ui->labelOutput->setText(QString::number(hwStatus.tempData.outputPower, 'f', 2) + " %");
    ui->labelTarget->setText(QString::number(hwStatus.tempData.targetTemp, 'f', 2) + " °C");
    ui->labelTarget_2->setText(QString::number(hwStatus.tempData.targetTemp, 'f', 2) + " °C");
    //ui->spinTemperature_2->setValue(hwStatus.tempData.targetTemp);
}

// 辅助函数：格式化温度显示（处理NaN）
QString MainWindow::formatTemperature(double temp) {
    if (qIsNaN(temp)) {
        return "N/A";
    } else {
        return QString::number(temp, 'f', 2) + " °C";
    }
}

void MainWindow::sendActionCommandToMCU(const QString &cmd, bool isAutoUpdate)
{
    if (!McuActionSocket || !McuActionSocket->isValid()) {
        if (!isAutoUpdate) {
            LOG_GENERAL("McuActionSocket UDP Socket not ready");
        }
        return;
    }

    QByteArray data = cmd.toUtf8();
    McuActionSocket->writeDatagram(data, QHostAddress(mcuIp), mcuPort);

    if (isAutoUpdate) {
        //writeAutoUpdateLog("发送自动更新命令: " + cmd);
    } else {
        //LOG_GENERAL("向温控单片机发送指令: " + cmd);
    }
}

